package com.xfcy.blog.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author 晓风残月Lx
 * @date 2023/5/13 9:52
 */
@Component
public class SpringUtils implements ApplicationContextAware {
    /**
     * Spring应用上下文环境
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取对象
     * @param name
     * @return 一个以所给名字注册的bean的实例
     * @param <T>
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name)  throws BeansException {
        return (T) getApplicationContext().getBean(name);
    }

    /**
     * 通过传入类型获取对象
     * @param clz
     * @return
     * @param <T>
     */
    public static <T> T getBean(Class<T> clz) {
        T bean = getApplicationContext().getBean(clz);
        return bean;
    }


}
